<template>
  <div class="home">
    <div class="home-left">
      <banner></banner>
      <home-article></home-article>
    </div>
    <div class="home-right">
      <home-author></home-author>
      <home-notice></home-notice>
      <home-source></home-source>
      <home-tag></home-tag>
      <home-chain></home-chain>
    </div>
  </div>
</template>

<script>
import homeAuthor from "@/components/home-author";
import homeNotice from "@/components/home/home-notice";
import homeTag from "@/components/home/home-tag";
import homeChain from "@/components/home/home-chain";
import HomeSource from "@/components/home/home-source";
import banner from "@/components/home/banner";
import homeArticle from "@/components/home/home-article";

export default {
  name: 'Home',
  data() {
    return {
      websocket: process.env.VUE_APP_WEBSOCKET_API + "/online",
    }
  },
  components: {
    banner,
    HomeSource,
    homeAuthor,
    homeTag,
    homeChain,
    homeArticle,
    homeNotice
  },
  created() {
    this.initWebsocket();
  },
  methods: {
    // 初始化
    initWebsocket() {
      if (typeof (WebSocket) === "undefined") {
        console.error("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.websocket);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      // 发送心跳消息
      var that = this;
      that.heartBeat = setInterval(function () {
        that.send("ping");
      }, 30 * 1000);
    },
    error: function () {
      console.error("连接错误");
    },
    getMessage: function (event) {
      this.$store.state.onlinePerson = event.data;
    },
    send(message) {
      this.socket.send(message);
    },
    close: function () {
      console.log("socket已经关闭");
    }
  }
}
</script>
<style scoped lang="less">
.home {
  margin-top: 20px;
  margin-bottom: 30px;
  display: flex;
}

.home-left {
  width: 1020px;
}

.home-right {
  width: 400px;
  margin-left: 20px;
}
</style>

